#include "guish.hpp"
#include <glob.h>

pair<string,string> tabComplete(string prefix, string suffix)
{
	if(!prefix.size())
		return pair<string,string>(prefix, suffix);
	
	TaggedString tagged(prefix);
	// Get the part of the prefix that corresponds to the current argument
	int pos = prefix.size()-1;
	for(; pos>=0; pos--)
	{
		if(tagged.isQuoted(pos) || tagged.isEscaped(pos))
			continue;
		if(tagged.isQuote(pos) || tagged[pos]==' '||tagged[pos]=='\t'||tagged[pos]=='\n') {
			pos++;
			break;
		}
	}
	string commandStart = prefix.substr(0, pos);
	string argStart = prefix.substr(pos, prefix.length()-pos) + "*";
	
	glob_t expansions;
	glob(argStart.c_str(), GLOB_MARK, NULL, &expansions);
	
	// If no possible expansions found, tab completion does nothing
	if(!expansions.gl_pathc) {
		globfree(&expansions);
		return pair<string,string>(prefix,suffix);
	}
	
	// Find the longest common prefix among matches
	string commonPrefix = expansions.gl_pathv[0];
	
	for(int ii=1; ii<(int)expansions.gl_pathc; ii++)
	{
		const char *expansion = expansions.gl_pathv[ii];
		int len = strlen(expansion);
		
		int commonPrefixLen = 0;
		for(; commonPrefixLen<min(len, (int)commonPrefix.length()); commonPrefixLen++)
		{
			if(commonPrefix[commonPrefixLen] != expansion[commonPrefixLen])
				break;
		}
		
		commonPrefix = commonPrefix.substr(0, commonPrefixLen);
	}
	
	globfree(&expansions);
	
	return pair<string,string>(
		commandStart+commonPrefix,
		suffix
		);
}

